package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;

//转到查看购物车界面
public class ViewCardServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //如果账号未登录，显示空
        //如果账号已经登录，则获取数据库中的信息
        Account account = (Account) session.getAttribute("account");
        CatalogService catalogService = new CatalogService();
        if(account == null){
            request.getRequestDispatcher(VIEW_CART).forward(request,response);
        }else{
            //加载数据库中的购物车
            Cart cart = catalogService.getCartByUsername(account.getUsername());

            //时间
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = tempDate.format(new java.util.Date());
            //信息
            String info = "查看购物车界面";
            Log log = new Log(account.getUsername(),datetime,info);
            //添加log
            new AccountService().addLog(log);
            session.setAttribute("cart",cart);
        }
        request.getRequestDispatcher(VIEW_CART).forward(request,response);
    }
}
